﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace AvaMaid
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        public static extern void SetForegroundWindow(IntPtr hwnd);

        public Mutex AppMutex;

        public Services.IPCService _ipcService;

        private void StartIPCService()
        {
            _ipcService = new Services.IPCService();
            _ipcService.Start();
        }



        private void StopIPCService()
        {
            _ipcService?.Close();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            if (!CheckMutex(e)) return;
            StartIPCService();
            if (e.Args != null && e.Args.Length > 0) _ipcService.SendLazyMessage(string.Join(",", e.Args));
        }


        private bool CheckMutex(StartupEventArgs e)
        {
            /*创建具有唯一名称的互斥锁*/
            AppMutex = new Mutex(true, "AvaMaid", out var createdNew);

            if (!createdNew)
            {
                var current = Process.GetCurrentProcess();

                foreach (var process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
                Shutdown();
                return false;
            }
            else
            {
                //var splashScreen = new SplashScreen("Resources/Img/Cover.png");
                //splashScreen.Show(true);

                base.OnStartup(e);
                return true;
            }
        }
    }
}
